<template>
  <div class="score-statistics-section">
    <h3 class="section-title">成绩统计信息</h3>
    <el-divider />
    
    <div v-loading="loading" class="statistics-content">
      <!-- 如果没有成绩数据 -->
      <el-empty v-if="!hasScoreData" description="暂无成绩数据">
        <template #description>
          <div>
            <p>当前教学任务暂无成绩数据</p>
            <p v-if="!teachingMissionIds || teachingMissionIds.length === 0">
              请先选择教学任务
            </p>
          </div>
        </template>
      </el-empty>
      
      <!-- 多标签页成绩统计 -->
      <el-tabs v-else v-model="activeTab" type="card" class="score-tabs">
        <!-- 总成绩标签页 -->
        <el-tab-pane label="总成绩" name="total">
          <div class="tab-content">
            <!-- 基本统计数据表 -->
            <div class="statistics-table-section">
              <h4>统计数据</h4>
              <el-table :data="totalScoreTableData" border style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="name" label="统计项目" width="150" />
                <el-table-column prop="totalCount" label="总人数" width="80" />
                <el-table-column prop="averageScore" label="平均分" width="80" />
                <el-table-column prop="medianScore" label="中位数" width="80" />
                <el-table-column prop="maxScore" label="最高分" width="80" />
                <el-table-column prop="minScore" label="最低分" width="80" />
                <el-table-column prop="standardDeviation" label="标准差" width="80" />
              </el-table>
            </div>
            
            <!-- 分段统计表 -->
            <div class="segment-table-section">
              <h4>分段统计</h4>
              <el-table :data="totalScoreSegmentData" border style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="name" label="统计项目" width="150" />
                <el-table-column label="分段统计" min-width="400">
                  <template #default="scope">
                    <div class="score-segments">
                      <span v-for="(segment, index) in scope.row.segments" :key="index" class="segment-item">
                        {{ segment.range }}: {{ segment.count }}人 ({{ segment.percentage }}%)
                      </span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分段统计图表 -->
              <div class="segment-charts-section">
                <h4>分段统计图表</h4>
                
                <!-- 图表视图切换 -->
                <div class="chart-view-toggle" v-if="scoreData.length > 1">
                  <el-radio-group v-model="totalChartViewType" size="small" style="margin-bottom: 15px;">
                    <el-radio-button value="overall">总体分布</el-radio-button>
                    <el-radio-button value="comparison">对比分析</el-radio-button>
                  </el-radio-group>
                </div>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="chart-container">
                      <h5>柱状图</h5>
                      <v-chart 
                        v-if="totalScoreSegmentData.length > 0 && chartsReady"
                        :option="getTotalScoreBarChartOption()" 
                        style="height: 300px; width: 100%;" 
                        autoresize
                      />
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="chart-container">
                      <h5>饼图</h5>
                      <v-chart 
                        v-if="totalScoreSegmentData.length > 0 && chartsReady"
                        :option="getTotalScorePieChartOption()" 
                        style="height: 300px; width: 100%;" 
                        autoresize
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 单项成绩标签页 -->
        <el-tab-pane 
          v-for="examPart in examPartStatistics" 
          :key="examPart.id" 
          :label="`${examPart.name} (${examPart.proportion}%)`" 
          :name="`part-${examPart.id}`"
        >
          <div class="tab-content">
            <!-- 单项成绩统计数据表 -->
            <div class="statistics-table-section">
              <h4>{{ examPart.name }}统计数据</h4>
              <el-table :data="getPartScoreTableData(examPart)" border style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="name" label="统计项目" width="150" />
                <el-table-column prop="totalCount" label="总人数" width="80" />
                <el-table-column prop="averageScore" label="平均分" width="80" />
                <el-table-column prop="medianScore" label="中位数" width="80" />
                <el-table-column prop="maxScore" label="最高分" width="80" />
                <el-table-column prop="minScore" label="最低分" width="80" />
                <el-table-column prop="standardDeviation" label="标准差" width="80" />
              </el-table>
            </div>
            
            <!-- 单项成绩分段统计表 -->
            <div class="segment-table-section">
              <h4>{{ examPart.name }}分段统计</h4>
              <el-table :data="getPartScoreSegmentData(examPart)" border style="width: 100%; margin-bottom: 20px;">
                <el-table-column prop="name" label="统计项目" width="150" />
                <el-table-column label="分段统计" min-width="400">
                  <template #default="scope">
                    <div class="score-segments">
                      <span v-for="(segment, index) in scope.row.segments" :key="index" class="segment-item">
                        {{ segment.range }}: {{ segment.count }}人 ({{ segment.percentage }}%)
                      </span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 单项成绩分段统计图表 -->
              <div class="segment-charts-section">
                <h4>{{ examPart.name }}分段统计图表</h4>
                
                <!-- 图表视图切换 -->
                <div class="chart-view-toggle" v-if="examPart.missions && examPart.missions.length > 1">
                  <el-radio-group :model-value="partChartViewType[examPart.id] || 'overall'" 
                                  @update:model-value="(val) => updatePartChartViewType(examPart.id, val)"
                                  size="small" style="margin-bottom: 15px;">
                    <el-radio-button value="overall">总体分布</el-radio-button>
                    <el-radio-button value="comparison">对比分析</el-radio-button>
                  </el-radio-group>
                </div>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <div class="chart-container">
                      <h5>柱状图</h5>
                      <v-chart 
                        v-if="getPartScoreSegmentData(examPart).length > 0 && chartsReady"
                        :option="getPartScoreBarChartOption(examPart)" 
                        style="height: 300px; width: 100%;" 
                        autoresize
                      />
                    </div>
                  </el-col>
                  <el-col :span="12">
                    <div class="chart-container">
                      <h5>饼图</h5>
                      <v-chart 
                        v-if="getPartScoreSegmentData(examPart).length > 0 && chartsReady"
                        :option="getPartScorePieChartOption(examPart)" 
                        style="height: 300px; width: 100%;" 
                        autoresize
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { scoreApi } from '@/api/score'
import { ElMessage } from 'element-plus'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import {
  CanvasRenderer
} from 'echarts/renderers'
import {
  BarChart,
  PieChart
} from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册必要的组件
use([
  CanvasRenderer,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

export default {
  name: 'ScoreStatistics',
  components: {
    VChart
  },
  props: {
    teachingMissionIds: {
      type: Array,
      default: () => []
    },
    courseId: {
      type: [String, Number],
      default: null
    },
    termId: {
      type: [String, Number],
      default: null
    }
  },
  setup(props) {
    const loading = ref(false)
    const scoreData = ref([])
    const examPartStatistics = ref([])
    const activeTab = ref('total')
    const chartsReady = ref(false)
    const totalChartViewType = ref('overall') // 'overall' 或 'comparison'
    const partChartViewType = ref({}) // 存储每个单项成绩的视图类型

    // 是否有成绩数据
    const hasScoreData = computed(() => {
      return scoreData.value.length > 0 || examPartStatistics.value.length > 0
    })

    // 计算分段范围（支持不同分制）
    const getScoreSegments = (scores, scoreType = 'PERCENTAGE') => {
      let segments = []
      
      if (scoreType === 'TWO_LEVEL') {
        segments = [
          { range: '及格', min: 60, max: 100 },
          { range: '不及格', min: 0, max: 59.99 }
        ]
      } else if (scoreType === 'FOUR_LEVEL') {
        segments = [
          { range: '优秀', min: 90, max: 100 },
          { range: '良好', min: 80, max: 89.99 },
          { range: '及格', min: 60, max: 79.99 },
          { range: '不及格', min: 0, max: 59.99 }
        ]
      } else if (scoreType === 'FIVE_LEVEL') {
        segments = [
          { range: '优秀', min: 90, max: 100 },
          { range: '良好', min: 80, max: 89.99 },
          { range: '中等', min: 70, max: 79.99 },
          { range: '及格', min: 60, max: 69.99 },
          { range: '不及格', min: 0, max: 59.99 }
        ]
      } else {
        // 百分制：以10分为一段
        segments = [
          { range: '90-100', min: 90, max: 100 },
          { range: '80-89', min: 80, max: 89.99 },
          { range: '70-79', min: 70, max: 79.99 },
          { range: '60-69', min: 60, max: 69.99 },
          { range: '50-59', min: 50, max: 59.99 },
          { range: '0-49', min: 0, max: 49.99 }
        ]
      }

      return segments.map(segment => {
        const count = scores.filter(score => {
          const numScore = parseFloat(score)
          return !isNaN(numScore) && numScore >= segment.min && numScore <= segment.max
        }).length
        
        const percentage = scores.length > 0 ? Math.round((count / scores.length) * 100) : 0
        return {
          ...segment,
          count,
          percentage
        }
      })
    }

    // 计算统计数据
    const calculateStatistics = (scores, name) => {
      if (!scores || scores.length === 0) {
        return {
          name,
          totalCount: 0,
          averageScore: 0,
          maxScore: 0,
          minScore: 0,
          medianScore: 0,
          standardDeviation: 0
        }
      }

      const numScores = scores.map(s => parseFloat(s)).filter(s => !isNaN(s))
      const sum = numScores.reduce((a, b) => a + b, 0)
      const average = sum / numScores.length
      
      const sortedScores = numScores.sort((a, b) => a - b)
      const median = sortedScores.length % 2 === 0 
        ? (sortedScores[sortedScores.length / 2 - 1] + sortedScores[sortedScores.length / 2]) / 2
        : sortedScores[Math.floor(sortedScores.length / 2)]

      const variance = numScores.reduce((acc, score) => acc + Math.pow(score - average, 2), 0) / numScores.length
      const standardDeviation = Math.sqrt(variance)

      return {
        name,
        totalCount: numScores.length,
        averageScore: Math.round(average * 100) / 100,
        maxScore: Math.max(...numScores),
        minScore: Math.min(...numScores),
        medianScore: Math.round(median * 100) / 100,
        standardDeviation: Math.round(standardDeviation * 100) / 100
      }
    }

    // 总成绩统计数据表格数据
    const totalScoreTableData = computed(() => {
      if (scoreData.value.length === 0) return []
      
      const result = []
      
      // 总体统计（第一行）
      const allScores = scoreData.value.flatMap(mission => 
        mission.scores ? mission.scores.map(s => s.totalScore || s.score || 0) : []
      )
      result.push(calculateStatistics(allScores, '总体'))
      
      // 各教学任务统计（后续行）
      scoreData.value.forEach(mission => {
        if (mission.scores && mission.scores.length > 0) {
          const missionScores = mission.scores.map(s => s.totalScore || s.score || 0)
          result.push(calculateStatistics(missionScores, mission.missionName))
        }
      })
      
      return result
    })

    // 总成绩分段统计表格数据
    const totalScoreSegmentData = computed(() => {
      if (scoreData.value.length === 0) return []
      
      const result = []
      
      // 总体分段统计（第一行）
      const allScores = scoreData.value.flatMap(mission => 
        mission.scores ? mission.scores.map(s => s.totalScore || s.score || 0) : []
      )
      result.push({
        name: '总体',
        segments: getScoreSegments(allScores)
      })
      
      // 各教学任务分段统计（后续行）
      scoreData.value.forEach(mission => {
        if (mission.scores && mission.scores.length > 0) {
          const missionScores = mission.scores.map(s => s.totalScore || s.score || 0)
          result.push({
            name: mission.missionName,
            segments: getScoreSegments(missionScores)
          })
        }
      })
      
      return result
    })

    // 获取单项成绩统计数据表格数据
    const getPartScoreTableData = (examPart) => {
      if (!examPart.missions || examPart.missions.length === 0) return []
      
      const result = []
      
      // 总体统计（第一行）
      const allScores = examPart.missions.flatMap(mission => mission.scores || [])
      result.push(calculateStatistics(allScores, '总体'))
      
      // 各教学任务统计（后续行）
      examPart.missions.forEach(mission => {
        result.push(calculateStatistics(mission.scores || [], mission.missionName))
      })
      
      return result
    }

    // 获取单项成绩分段统计表格数据
    const getPartScoreSegmentData = (examPart) => {
      if (!examPart.missions || examPart.missions.length === 0) return []
      
      const result = []
      
      // 总体分段统计（第一行）
      const allScores = examPart.missions.flatMap(mission => mission.scores || [])
      result.push({
        name: '总体',
        segments: getScoreSegments(allScores, examPart.scoreType)
      })
      
      // 各教学任务分段统计（后续行）
      examPart.missions.forEach(mission => {
        result.push({
          name: mission.missionName,
          segments: getScoreSegments(mission.scores || [], examPart.scoreType)
        })
      })
      
      return result
    }

    // 获取成绩数据
    const fetchScoreData = async () => {
      if (!props.teachingMissionIds || props.teachingMissionIds.length === 0) {
        scoreData.value = []
        examPartStatistics.value = []
        chartsReady.value = false
        return
      }

      try {
        loading.value = true
        
        // 获取总成绩统计数据
        const scorePromises = props.teachingMissionIds.map(async (missionId) => {
          try {
            const statistics = await scoreApi.getScoreStatistics(missionId)
            const missionInfo = await scoreApi.getMissionInfo(missionId)
            
            return {
              missionId,
              missionName: missionInfo.name || missionInfo.courseName || `教学任务${missionId}`,
              scores: statistics.scores || [],
              statistics: statistics.statistics
            }
          } catch (error) {
            console.error(`获取教学任务 ${missionId} 成绩失败:`, error)
            return {
              missionId,
              missionName: `教学任务${missionId}`,
              scores: [],
              statistics: null
            }
          }
        })

        const results = await Promise.all(scorePromises)
        scoreData.value = results.filter(result => result !== null)
        
        // 获取单项成绩统计数据
        await fetchExamPartStatistics()
        
        // 延迟启用图表渲染，确保DOM已经准备好
        await nextTick()
        
        // 等待更长时间确保DOM完全渲染，特别是在审核页面等复杂布局中
        setTimeout(() => {
          // 检查容器是否有足够的尺寸
          const containers = document.querySelectorAll('.chart-container')
          let allReady = true
          
          containers.forEach(container => {
            if (container.clientWidth < 100 || container.clientHeight < 100) {
              allReady = false
            }
          })
          
          if (allReady || containers.length === 0) {
            chartsReady.value = true
          } else {
            // 如果DOM还没准备好，再等一会儿，然后强制显示
            setTimeout(() => {
              chartsReady.value = true
            }, 500)
          }
        }, 300)
        
      } catch (error) {
        console.error('获取成绩统计数据失败:', error)
        ElMessage.error('获取成绩统计数据失败')
        scoreData.value = []
        examPartStatistics.value = []
      } finally {
        loading.value = false
      }
    }

    // 获取单项成绩统计数据
    const fetchExamPartStatistics = async () => {
      if (!props.teachingMissionIds || props.teachingMissionIds.length === 0) {
        examPartStatistics.value = []
        return
      }

      try {
        // 为每个教学任务分别获取单项成绩统计
        const examPartPromises = props.teachingMissionIds.map(async (missionId) => {
          try {
            const partStatistics = await scoreApi.getExamPartStatistics(missionId)
            const missionInfo = await scoreApi.getMissionInfo(missionId)
            const missionName = missionInfo.name || missionInfo.courseName || `教学任务${missionId}`
            
            // 为每个成绩组成添加教学任务信息
            return (partStatistics || []).map(part => ({
              ...part,
              missionId: missionId,
              missionName: missionName
            }))
          } catch (error) {
            console.error(`获取教学任务 ${missionId} 单项成绩统计失败:`, error)
            return []
          }
        })

        const results = await Promise.all(examPartPromises)
        const allExamParts = results.flat()
        
        // 按考核项名称和比例分组合并，相同的考核项显示在同一个标签页
        const examPartMap = new Map()
        allExamParts.forEach(part => {
          // 使用考核项名称和比例作为分组key，相同的考核项会被合并
          const partKey = `${part.name}-${part.proportion}`
          
          if (!examPartMap.has(partKey)) {
            examPartMap.set(partKey, {
              id: part.originalId || part.id, // 使用原始ID
              name: part.name,
              proportion: part.proportion,
              scoreType: part.scoreType,
              missions: []
            })
          }
          
          // 关键修复：每个教学任务的API返回一个考核项，该考核项的missions包含该任务的成绩数据
          // 我们需要将这个mission重新标记上教学任务信息，并添加到合并后的missions中
          if (part.missions && part.missions.length > 0) {
            // 通常每个教学任务返回的考核项只有一个mission（代表该教学任务的数据）
            const mission = part.missions[0]; // 取第一个mission
            const missionWithInfo = {
              ...mission,
              missionId: part.missionId,
              missionName: part.missionName
            }
            examPartMap.get(partKey).missions.push(missionWithInfo)
          }
        })
        
        examPartStatistics.value = Array.from(examPartMap.values())
        
      } catch (error) {
        console.error('获取单项成绩统计数据失败:', error)
        examPartStatistics.value = []
      }
    }

    // 监听props变化
    watch(
      () => [props.teachingMissionIds, props.courseId, props.termId], 
      (newVal) => {
        fetchScoreData()
      },
      { deep: true }
    )

    // 组件挂载后初始化数据
    onMounted(() => {
      if (props.teachingMissionIds && props.teachingMissionIds.length > 0) {
        // 等待DOM完全渲染
        nextTick(() => {
          fetchScoreData()
        })
      }
    })

    // 更新单项成绩图表视图类型
    const updatePartChartViewType = (partId, viewType) => {
      partChartViewType.value[partId] = viewType
    }

    // 生成总成绩分段统计柱状图配置
    const getTotalScoreBarChartOption = () => {
      if (totalScoreSegmentData.value.length === 0) return {}
      
      if (totalChartViewType.value === 'comparison' && scoreData.value.length > 1) {
        // 对比模式：显示多个教学任务的对比，排除总体数据
        const allSegments = totalScoreSegmentData.value[0]?.segments || []
        const categories = allSegments.map(s => s.range)
        
        // 过滤掉第一行的总体数据，只显示各教学任务的数据
        const series = totalScoreSegmentData.value.slice(1).map((data, index) => ({
          name: data.name,
          type: 'bar',
          data: data.segments.map(s => s.count),
          itemStyle: {
            color: `hsl(${index * 60}, 70%, 60%)`
          }
        }))
        
        return {
          title: {
            text: '总成绩分段分布对比',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              let result = `${params[0].name}<br/>`
              params.forEach(param => {
                // 由于排除了总体数据，需要在slice(1)的数据中查找
                const segmentData = totalScoreSegmentData.value.slice(1).find(d => d.name === param.seriesName)
                const segment = segmentData?.segments[param.dataIndex]
                result += `${param.seriesName}: ${param.value}人 (${segment?.percentage || 0}%)<br/>`
              })
              return result
            }
          },
          legend: {
            top: '30px',
            data: series.map(s => s.name)
          },
          xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series
        }
      } else {
        // 总体模式：只显示第一行（总体）的数据
        const totalData = totalScoreSegmentData.value[0]
        if (!totalData || !totalData.segments) return {}
        
        const segments = totalData.segments
        const categories = segments.map(s => s.range)
        const counts = segments.map(s => s.count)
        
        return {
          title: {
            text: '总成绩分段分布',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              const data = params[0]
              const segment = segments[data.dataIndex]
              return `${data.name}<br/>人数: ${data.value}<br/>占比: ${segment.percentage}%`
            }
          },
          xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series: [{
            name: '人数',
            type: 'bar',
            data: counts,
            itemStyle: {
              color: '#409eff'
            }
          }]
        }
      }
    }

    // 生成总成绩分段统计饼图配置
    const getTotalScorePieChartOption = () => {
      if (totalScoreSegmentData.value.length === 0) return {}
      
      // 饼图始终显示总体数据（第一行）
      const totalData = totalScoreSegmentData.value[0]
      if (!totalData || !totalData.segments) return {}
      
      const pieData = totalData.segments
        .filter(s => s.count > 0)
        .map(s => ({
          name: s.range,
          value: s.count
        }))
      
      const title = totalChartViewType.value === 'comparison' && scoreData.value.length > 1
        ? '总体成绩分段分布'
        : '总成绩分段分布'
      
      return {
        title: {
          text: title,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '人数',
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
    }

    // 生成单项成绩分段统计柱状图配置
    const getPartScoreBarChartOption = (examPart) => {
      const segmentData = getPartScoreSegmentData(examPart)
      if (segmentData.length === 0) return {}
      
      const currentViewType = partChartViewType.value[examPart.id] || 'overall'
      
      if (currentViewType === 'comparison' && examPart.missions && examPart.missions.length > 1) {
        // 对比模式：显示多个教学任务的对比，排除总体数据
        const allSegments = segmentData[0]?.segments || []
        const categories = allSegments.map(s => s.range)
        
        // 过滤掉第一行的总体数据，只显示各教学任务的数据
        const series = segmentData.slice(1).map((data, index) => ({
          name: data.name,
          type: 'bar',
          data: data.segments.map(s => s.count),
          itemStyle: {
            color: `hsl(${index * 60 + 120}, 70%, 60%)`
          }
        }))
        
        return {
          title: {
            text: `${examPart.name}分段分布对比`,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              let result = `${params[0].name}<br/>`
              params.forEach(param => {
                // 由于排除了总体数据，需要在slice(1)的数据中查找
                const segmentDataItem = segmentData.slice(1).find(d => d.name === param.seriesName)
                const segment = segmentDataItem?.segments[param.dataIndex]
                result += `${param.seriesName}: ${param.value}人 (${segment?.percentage || 0}%)<br/>`
              })
              return result
            }
          },
          legend: {
            top: '30px',
            data: series.map(s => s.name)
          },
          xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series
        }
      } else {
        // 总体模式：只显示第一行（总体）的数据
        const totalData = segmentData[0]
        if (!totalData || !totalData.segments) return {}
        
        const segments = totalData.segments
        const categories = segments.map(s => s.range)
        const counts = segments.map(s => s.count)
        
        return {
          title: {
            text: `${examPart.name}分段分布`,
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: (params) => {
              const data = params[0]
              const segment = segments[data.dataIndex]
              return `${data.name}<br/>人数: ${data.value}<br/>占比: ${segment.percentage}%`
            }
          },
          xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '人数'
          },
          series: [{
            name: '人数',
            type: 'bar',
            data: counts,
            itemStyle: {
              color: '#67c23a'
            }
          }]
        }
      }
    }

    // 生成单项成绩分段统计饼图配置
    const getPartScorePieChartOption = (examPart) => {
      const segmentData = getPartScoreSegmentData(examPart)
      if (segmentData.length === 0) return {}
      
      // 使用第一行（总体）的数据
      const totalData = segmentData[0]
      if (!totalData || !totalData.segments) return {}
      
      const pieData = totalData.segments
        .filter(s => s.count > 0)
        .map(s => ({
          name: s.range,
          value: s.count
        }))
      
      return {
        title: {
          text: `${examPart.name}分段分布`,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          name: '人数',
          type: 'pie',
          radius: '50%',
          center: ['50%', '60%'],
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
    }

    return {
      loading,
      hasScoreData,
      activeTab,
      scoreData,
      totalScoreTableData,
      totalScoreSegmentData,
      examPartStatistics,
      getPartScoreTableData,
      getPartScoreSegmentData,
      getTotalScoreBarChartOption,
      getTotalScorePieChartOption,
      getPartScoreBarChartOption,
      getPartScorePieChartOption,
      chartsReady,
      totalChartViewType,
      partChartViewType,
      updatePartChartViewType,
      teachingMissionIds: computed(() => props.teachingMissionIds)
    }
  }
}
</script>

<style scoped>
.score-statistics-section {
  margin: 30px 0;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 15px;
}

.statistics-content {
  min-height: 200px;
}

.score-tabs {
  margin-top: 10px;
}

.tab-content {
  padding: 20px 0;
}

.statistics-table-section,
.segment-table-section {
  margin-bottom: 30px;
}

.segment-charts-section {
  margin-top: 30px;
}

.chart-container {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  min-width: 300px;
  min-height: 350px;
}

.chart-container h5 {
  text-align: center;
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.chart-view-toggle {
  text-align: center;
  margin-bottom: 20px;
}

.chart-view-toggle .el-radio-group {
  background: #f5f7fa;
  padding: 4px;
  border-radius: 6px;
}

.statistics-table-section h4,
.segment-table-section h4,
.segment-charts-section h4 {
  color: #606266;
  font-size: 16px;
  margin-bottom: 15px;
}

.score-segments {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.segment-item {
  background: #f0f2f5;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
}

:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
}

:deep(.el-empty__description p) {
  margin: 8px 0;
  color: #606266;
}
</style>
